import Modal from 'react-bootstrap/Modal';
import { useState, useEffect } from 'react';
import wxAuthClient from '../utils/wxAuthClient';
import userClient from '../utils/userClient';

const WxAuthForm = ({ isShow, onHide }) => {
    const [user, setUser] = useState(null);


    useEffect(() => {
        let interval;
        setUser(userClient.getUser());
        if (isShow && !user) {
            interval = setInterval(async () => {
                const user = await wxAuthClient.getUser();
                if (user) {
                    clearInterval(interval);
                    setUser(user);
                    userClient.setUser(user);
                    setTimeout(() => {
                        window.location.reload();
                    }, 3000);
                }
            }, 1000);
        }
        return () => clearInterval(interval);
    }, [isShow]);


    const handleClose = () => {
        if (onHide && typeof onHide === 'function') {
            onHide();
        }
    }
    return (<>
        <Modal
            show={isShow}
            onHide={handleClose}
            backdrop="static"
        >
            <Modal.Header closeButton>
                <Modal.Title>微信公众号登录</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                <div style={{ textAlign: 'center' }}>
                    <img src="https://jishuba.cn/wp-content/plugins/idea-canvas/images/jsb-bar-code.png" alt="wechat qr code" 
                        style={{ width: '300px' }}
                    />
                    {user && <><p>你已登录成功！</p><p>欢迎你，{user.username}</p></>}
                    {!user && <><p>请使用微信扫码登录</p>
                        <p>扫码关注发送暗号：666</p></>}
                </div>
            </Modal.Body>
        </Modal>
    </>)
}

export default WxAuthForm;